<template>
  <div class="reconciliation-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>对账管理</span>
          <el-button-group>
            <el-button type="primary" @click="handleReconciliation">
              <el-icon><Check /></el-icon>开始对账
            </el-button>
            <el-button type="success" @click="exportReconciliation">
              <el-icon><Download /></el-icon>导出对账单
            </el-button>
          </el-button-group>
        </div>
      </template>

      <!-- 对账概览 -->
      <el-row :gutter="20" class="statistics-cards">
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Money /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">待对账金额</div>
                <div class="stat-amount">¥{{ pendingAmount.toFixed(2) }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-icon warning">
                <el-icon><Warning /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">差异订单数</div>
                <div class="stat-amount">{{ differenceCount }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-icon success">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">已对账笔数</div>
                <div class="stat-amount">{{ reconciledCount }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-icon info">
                <el-icon><Timer /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">待对账笔数</div>
                <div class="stat-amount">{{ pendingCount }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 搜索表单 -->
      <div class="search-section">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="对账日期">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item label="对账状态">
            <el-select v-model="searchForm.status" placeholder="请选择对账状态">
              <el-option label="全部" value="" />
              <el-option label="待对账" value="pending" />
              <el-option label="对账中" value="processing" />
              <el-option label="已完成" value="completed" />
              <el-option label="有差异" value="difference" />
            </el-select>
          </el-form-item>
          <el-form-item label="支付渠道">
            <el-select
              v-model="searchForm.channel"
              placeholder="请选择支付渠道"
            >
              <el-option label="全部" value="" />
              <el-option label="微信支付" value="wechat" />
              <el-option label="支付宝" value="alipay" />
              <el-option label="银联" value="unionpay" />
            </el-select>
          </el-form-item>
          <el-form-item label="订单号">
            <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon>重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 对账列表 -->
      <el-table
        v-loading="loading"
        :data="reconciliationList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          prop="orderNo"
          label="订单号"
          min-width="180"
          sortable="custom"
          show-overflow-tooltip
        />
        <el-table-column
          prop="transactionNo"
          label="交易流水号"
          min-width="180"
          sortable="custom"
          show-overflow-tooltip
        />
        <el-table-column
          prop="channel"
          label="支付渠道"
          min-width="120"
          sortable="custom"
        >
          <template #default="{ row }">
            <el-tag>{{ getChannelLabel(row.channel) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="orderAmount"
          label="订单金额"
          min-width="120"
          sortable="custom"
        >
          <template #default="{ row }">
            ¥{{ row.orderAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="actualAmount"
          label="实收金额"
          min-width="120"
          sortable="custom"
        >
          <template #default="{ row }">
            ¥{{ row.actualAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="difference"
          label="差异金额"
          min-width="120"
          sortable="custom"
        >
          <template #default="{ row }">
            <span :class="{ 'text-danger': row.difference !== 0 }">
              ¥{{ row.difference.toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="交易时间"
          min-width="160"
          sortable="custom"
        />
        <el-table-column
          prop="status"
          label="对账状态"
          min-width="100"
          sortable="custom"
        >
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="120" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                type="primary"
                link
                :disabled="row.status === 'completed'"
                @click="handleSingleReconciliation(row)"
              >
                对账
              </el-button>
              <el-button type="primary" link @click="viewDetail(row)">
                详情
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
        <template #empty>
          <div class="empty-state">
            <el-empty 
              description="暂无对账数据" 
              :image-size="200"
            >
              <div class="empty-text">暂无对账数据</div>
              <div class="empty-subtext">开始对账后将在此处显示对账记录</div>
            </el-empty>
          </div>
        </template>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 对账详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="对账详情" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单号">{{
          currentDetail.orderNo
        }}</el-descriptions-item>
        <el-descriptions-item label="交易流水号">{{
          currentDetail.transactionNo
        }}</el-descriptions-item>
        <el-descriptions-item label="支付渠道">
          <el-tag>{{ getChannelLabel(currentDetail.channel) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="对账状态">
          <el-tag :type="getStatusType(currentDetail.status)">
            {{ getStatusLabel(currentDetail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="订单金额"
          >¥{{ currentDetail.orderAmount?.toFixed(2) }}</el-descriptions-item
        >
        <el-descriptions-item label="实收金额"
          >¥{{ currentDetail.actualAmount?.toFixed(2) }}</el-descriptions-item
        >
        <el-descriptions-item label="差异金额">
          <span :class="{ 'text-danger': currentDetail.difference !== 0 }">
            ¥{{ currentDetail.difference?.toFixed(2) }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="交易时间">{{
          currentDetail.createTime
        }}</el-descriptions-item>
      </el-descriptions>

      <div class="detail-section mt-4">
        <h4>订单信息</h4>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="商品名称">{{
            currentDetail.productName
          }}</el-descriptions-item>
          <el-descriptions-item label="购买数量">{{
            currentDetail.quantity
          }}</el-descriptions-item>
          <el-descriptions-item label="单价"
            >¥{{ currentDetail.unitPrice?.toFixed(2) }}</el-descriptions-item
          >
          <el-descriptions-item label="优惠金额"
            >¥{{
              currentDetail.discountAmount?.toFixed(2)
            }}</el-descriptions-item
          >
          <el-descriptions-item label="买家账号">{{
            currentDetail.buyerAccount
          }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{
            currentDetail.buyerPhone
          }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <div
        class="detail-section mt-4"
        v-if="currentDetail.reconciliationRecords?.length"
      >
        <h4>对账记录</h4>
        <el-table
          :data="currentDetail.reconciliationRecords"
          style="width: 100%"
        >
          <el-table-column prop="operateTime" label="操作时间" width="160" />
          <el-table-column prop="operator" label="操作人" width="120" />
          <el-table-column prop="action" label="操作类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getActionType(row.action)">
                {{ getActionLabel(row.action) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="remark"
            label="备注"
            min-width="200"
            show-overflow-tooltip
          />
        </el-table>
      </div>
    </el-dialog>

    <!-- 对账确认弹窗 -->
    <el-dialog
      v-model="reconciliationDialogVisible"
      title="对账确认"
      width="1200px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="reconciliation-summary">
        <el-alert
          :title="
            hasDifference
              ? '注意：存在差异订单，请选择处理方式'
              : '请确认以下对账信息'
          "
          :type="hasDifference ? 'warning' : 'info'"
          :closable="false"
          class="mb-4"
        />

        <el-descriptions :column="2" border>
          <el-descriptions-item label="对账笔数"
            >{{ selectedRecords.length }}笔</el-descriptions-item
          >
          <el-descriptions-item label="总订单金额"
            >¥{{ getTotalOrderAmount() }}</el-descriptions-item
          >
          <el-descriptions-item label="总实收金额"
            >¥{{ getTotalActualAmount() }}</el-descriptions-item
          >
          <el-descriptions-item label="总差异金额">
            <span :class="{ 'text-danger': getTotalDifference() !== 0 }">
              ¥{{ getTotalDifference() }}
            </span>
          </el-descriptions-item>
        </el-descriptions>

        <div class="reconciliation-form mt-4">
          <el-form
            ref="reconciliationFormRef"
            :model="reconciliationForm"
            :rules="reconciliationRules"
            label-width="120px"
          >
            <el-form-item
              label="对账处理方式"
              prop="processType"
              v-if="hasDifference"
            >
              <el-radio-group v-model="reconciliationForm.processType">
                <el-radio label="adjust">调整差异</el-radio>
                <el-radio label="confirm">确认差异</el-radio>
                <el-radio label="split">拆分处理</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item
              label="差异处理说明"
              prop="differenceRemark"
              v-if="
                hasDifference && reconciliationForm.processType === 'adjust'
              "
            >
              <el-input
                v-model="reconciliationForm.differenceRemark"
                type="textarea"
                :rows="2"
                placeholder="请说明差异调整原因和处理方式"
              />
            </el-form-item>

            <el-form-item label="对账备注" prop="remark">
              <el-input
                v-model="reconciliationForm.remark"
                type="textarea"
                :rows="2"
                placeholder="请输入对账备注信息"
              />
            </el-form-item>

            <el-form-item label="处理人" prop="operator">
              <el-input
                v-model="reconciliationForm.operator"
                placeholder="请输入处理人姓名"
                style="width: 200px"
              />
            </el-form-item>
          </el-form>
        </div>

        <div class="reconciliation-records mt-4">
          <div class="section-header">
            <h4>对账明细</h4>
            <div class="actions">
              <el-button type="primary" link @click="handleExportDetail">
                <el-icon><Download /></el-icon>导出明细
              </el-button>
            </div>
          </div>

          <el-table
            :data="selectedRecords"
            style="width: 100%"
            max-height="400"
            :row-class-name="getRecordRowClass"
          >
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column
              prop="orderNo"
              label="订单号"
              min-width="180"
              show-overflow-tooltip
            />
            <el-table-column
              prop="transactionNo"
              label="交易流水号"
              min-width="180"
              show-overflow-tooltip
            />
            <el-table-column prop="channel" label="支付渠道" width="120">
              <template #default="{ row }">
                <el-tag>{{ getChannelLabel(row.channel) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="orderAmount" label="订单金额" width="120">
              <template #default="{ row }">
                ¥{{ row.orderAmount.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="actualAmount" label="实收金额" width="120">
              <template #default="{ row }">
                ¥{{ row.actualAmount.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="difference" label="差异金额" width="120">
              <template #default="{ row }">
                <span :class="{ 'text-danger': row.difference !== 0 }">
                  ¥{{ row.difference.toFixed(2) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="交易时间" width="160" />
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" link @click="viewDetail(row)">
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancelReconciliation">取 消</el-button>
          <el-button
            type="primary"
            @click="handleConfirmReconciliation"
            :loading="reconciliationLoading"
          >
            确认对账
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Money,
  Warning,
  CircleCheck,
  Timer,
  Search,
  Refresh,
  Check,
  Download,
} from "@element-plus/icons-vue";
import service from "@/api/axios";
import * as XLSX from "xlsx";

// 统计数据
const pendingAmount = ref(0);
const differenceCount = ref(0);
const reconciledCount = ref(0);
const pendingCount = ref(0);

// 搜索表单
const searchForm = reactive({
  dateRange: [],
  status: "",
  channel: "",
  orderNo: "",
  sort: "createTime",
  order: "descending",
});

// 表格数据
const loading = ref(false);
const reconciliationList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedRecords = ref([]);

// 详情对话框
const detailDialogVisible = ref(false);
const currentDetail = ref({});

// 对账弹窗相关
const reconciliationDialogVisible = ref(false);
const reconciliationLoading = ref(false);
const reconciliationFormRef = ref(null);
const reconciliationForm = reactive({
  processType: "confirm", // 处理方式：adjust-调整差异，confirm-确认差异，split-拆分处理
  differenceRemark: "", // 差异说明
  remark: "", // 对账备注
  operator: "", // 处理人
});

// 表单验证规则
const reconciliationRules = {
  processType: [
    { required: true, message: "请选择对账处理方式", trigger: "change" },
  ],
  differenceRemark: [
    { required: true, message: "请输入差异处理说明", trigger: "blur" },
  ],
  remark: [{ required: true, message: "请输入对账备注", trigger: "blur" }],
  operator: [{ required: true, message: "请输入处理人姓名", trigger: "blur" }],
};

// 判断是否存在差异
const hasDifference = computed(() => {
  return selectedRecords.value.some((record) => record.difference !== 0);
});

// 获取行样式
const getRecordRowClass = ({ row }) => {
  if (row.difference !== 0) {
    return "difference-row";
  }
  return "";
};

// 获取支付渠道标签
const getChannelLabel = (channel) => {
  const channels = {
    wechat: "微信支付",
    alipay: "支付宝",
    unionpay: "银联",
  };
  return channels[channel] || channel;
};

// 获取状态标签
const getStatusLabel = (status) => {
  const statuses = {
    pending: "待对账",
    processing: "对账中",
    completed: "已完成",
    difference: "有差异",
  };
  return statuses[status] || status;
};

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    pending: "warning",
    processing: "info",
    completed: "success",
    difference: "danger",
  };
  return types[status] || "info";
};

// 获取操作类型标签
const getActionLabel = (action) => {
  const actions = {
    start: "开始对账",
    confirm: "确认无误",
    adjust: "调整差异",
    complete: "完成对账",
  };
  return actions[action] || action;
};

// 获取操作类型样式
const getActionType = (action) => {
  const types = {
    start: "info",
    confirm: "success",
    adjust: "warning",
    complete: "primary",
  };
  return types[action] || "info";
};

// 处理排序变化
const handleSortChange = ({ prop, order }) => {
  if (prop) {
    searchForm.sort = prop;
    searchForm.order = order || "descending";
    handleSearch();
  }
};

// 搜索
const handleSearch = async () => {
  loading.value = true;
  try {
    // 构造查询参数
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      status: searchForm.status || undefined,
      channel: searchForm.channel || undefined,
      orderNo: searchForm.orderNo || undefined,
      sort: searchForm.sort,
      order: searchForm.order,
      startDate: searchForm.dateRange && searchForm.dateRange[0] ? searchForm.dateRange[0] : undefined,
      endDate: searchForm.dateRange && searchForm.dateRange[1] ? searchForm.dateRange[1] : undefined
    };

    // 调用API获取对账列表
    const res = await service.get('/admin/finance/reconciliation/list', { params });
    
    if (res.code === 200 && res.data) {
      reconciliationList.value = res.data.list || [];
      total.value = res.data.total || 0;
      
      // 更新统计数据
      await fetchReconciliationStatistics();
    } else {
      // 如果API调用不成功，使用模拟数据
      generateMockData();
    }
  } catch (error) {
    console.error("获取对账列表失败", error);
    // 使用模拟数据
    generateMockData();
  } finally {
    loading.value = false;
  }
};

// 生成模拟数据
const generateMockData = () => {
  // 模拟数据
  const mockData = Array.from({ length: 50 }, (_, index) => {
    const orderAmount = Math.random() * 10000;
    const actualAmount =
      orderAmount + (Math.random() > 0.7 ? Math.random() * 100 - 50 : 0);
    return {
      id: index + 1,
      orderNo: `ORDER${String(Date.now()).slice(-6)}${String(index + 1).padStart(4, "0")}`,
      transactionNo: `TX${String(Date.now()).slice(-6)}${String(index + 1).padStart(4, "0")}`,
      channel: ["wechat", "alipay", "unionpay"][
        Math.floor(Math.random() * 3)
      ],
      orderAmount: Number(orderAmount.toFixed(2)),
      actualAmount: Number(actualAmount.toFixed(2)),
      difference: Number((actualAmount - orderAmount).toFixed(2)),
      createTime: new Date(
        Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000,
      ).toLocaleString(),
      status: ["pending", "processing", "completed", "difference"][
        Math.floor(Math.random() * 4)
      ],
      productName: ["景区门票", "酒店住宿", "美食套餐", "文创商品"][
        Math.floor(Math.random() * 4)
      ],
      quantity: Math.floor(Math.random() * 5) + 1,
      unitPrice: Number(
        (orderAmount / (Math.floor(Math.random() * 5) + 1)).toFixed(2),
      ),
      discountAmount: Number((Math.random() * 100).toFixed(2)),
      buyerAccount: `user_${Math.random().toString(36).slice(-8)}`,
      buyerPhone: `1${Math.random().toString().slice(2, 13)}`,
      reconciliationRecords:
        Math.random() > 0.5
          ? [
              {
                operateTime: new Date(
                  Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000,
                ).toLocaleString(),
                operator: "管理员",
                action: ["start", "confirm", "adjust", "complete"][
                  Math.floor(Math.random() * 4)
                ],
                remark: "系统自动对账",
              },
            ]
          : [],
    };
  });

  // 更新统计数据
  pendingAmount.value = mockData
    .filter((item) => item.status === "pending")
    .reduce((sum, item) => sum + item.orderAmount, 0);
  differenceCount.value = mockData.filter(
    (item) => item.status === "difference",
  ).length;
  reconciledCount.value = mockData.filter(
    (item) => item.status === "completed",
  ).length;
  pendingCount.value = mockData.filter(
    (item) => item.status === "pending",
  ).length;

  // 根据搜索条件筛选数据
  let filteredData = [...mockData];

  if (searchForm.dateRange?.length === 2) {
    const startDate = new Date(searchForm.dateRange[0]).getTime();
    const endDate = new Date(searchForm.dateRange[1]).getTime();
    filteredData = filteredData.filter((item) => {
      const itemDate = new Date(item.createTime).getTime();
      return itemDate >= startDate && itemDate <= endDate;
    });
  }

  if (searchForm.status) {
    filteredData = filteredData.filter(
      (item) => item.status === searchForm.status,
    );
  }

  if (searchForm.channel) {
    filteredData = filteredData.filter(
      (item) => item.channel === searchForm.channel,
    );
  }

  if (searchForm.orderNo) {
    filteredData = filteredData.filter((item) =>
      item.orderNo.toLowerCase().includes(searchForm.orderNo.toLowerCase()),
    );
  }

  // 排序
  if (searchForm.sort) {
    filteredData.sort((a, b) => {
      let compareResult = 0;
      if (typeof a[searchForm.sort] === "string") {
        compareResult = a[searchForm.sort].localeCompare(b[searchForm.sort]);
      } else {
        compareResult = a[searchForm.sort] - b[searchForm.sort];
      }
      return searchForm.order === "ascending"
        ? compareResult
        : -compareResult;
    });
  }

  // 分页
  total.value = filteredData.length;
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  reconciliationList.value = filteredData.slice(start, end);
};

// 获取对账统计数据
const fetchReconciliationStatistics = async () => {
  try {
    const res = await service.get('/admin/finance/reconciliation/statistics');
    if (res.code === 200 && res.data) {
      pendingAmount.value = res.data.pendingAmount || 0;
      differenceCount.value = res.data.differenceCount || 0;
      reconciledCount.value = res.data.reconciledCount || 0;
      pendingCount.value = res.data.pendingCount || 0;
    }
  } catch (error) {
    console.error("获取对账统计数据失败", error);
    // 使用默认数据
  }
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    if (key === "sort") {
      searchForm[key] = "createTime";
    } else if (key === "order") {
      searchForm[key] = "descending";
    } else {
      searchForm[key] = "";
    }
  });
  searchForm.dateRange = [];
  currentPage.value = 1;
  handleSearch();
};

// 处理选择变化
const handleSelectionChange = (val) => {
  selectedRecords.value = val;
};

// 计算总金额
const getTotalOrderAmount = () => {
  return selectedRecords.value
    .reduce((sum, record) => sum + record.orderAmount, 0)
    .toFixed(2);
};

const getTotalActualAmount = () => {
  return selectedRecords.value
    .reduce((sum, record) => sum + record.actualAmount, 0)
    .toFixed(2);
};

const getTotalDifference = () => {
  return selectedRecords.value
    .reduce((sum, record) => sum + record.difference, 0)
    .toFixed(2);
};

// 开始对账
const handleReconciliation = () => {
  if (selectedRecords.value.length === 0) {
    ElMessage.warning("请选择要对账的记录");
    return;
  }
  reconciliationDialogVisible.value = true;
};

// 查看详情
const viewDetail = async (row) => {
  try {
    // 调用API获取对账详情
    const res = await service.get(`/admin/finance/reconciliation/detail/${row.id}`);
    if (res.code === 200 && res.data) {
      currentDetail.value = res.data;
    } else {
      currentDetail.value = row;
    }
  } catch (error) {
    console.error("获取对账详情失败", error);
    currentDetail.value = row;
  }
  detailDialogVisible.value = true;
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  handleSearch();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  handleSearch();
};

// 导出对账单
const exportReconciliation = () => {
  if (reconciliationList.value.length === 0) {
    ElMessage.warning("暂无数据可导出");
    return;
  }

  try {
    // 准备导出数据
    const exportData = reconciliationList.value.map(item => ({
      '订单号': item.orderNo,
      '交易流水号': item.transactionNo,
      '支付渠道': getChannelLabel(item.channel),
      '订单金额': item.orderAmount.toFixed(2),
      '实收金额': item.actualAmount.toFixed(2),
      '差异金额': item.difference.toFixed(2),
      '交易时间': item.createTime,
      '对账状态': getStatusLabel(item.status)
    }));

    // 创建工作簿
    const wb = XLSX.utils.book_new();
    
    // 将数据转换为工作表
    const ws = XLSX.utils.json_to_sheet(exportData);
    
    // 设置列宽
    const colWidths = [
      { wch: 25 }, // 订单号
      { wch: 25 }, // 交易流水号
      { wch: 15 }, // 支付渠道
      { wch: 15 }, // 订单金额
      { wch: 15 }, // 实收金额
      { wch: 15 }, // 差异金额
      { wch: 20 }, // 交易时间
      { wch: 15 }  // 对账状态
    ];
    ws['!cols'] = colWidths;
    
    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(wb, ws, "对账数据");
    
    // 生成并下载Excel文件
    XLSX.writeFile(wb, `对账单_${new Date().toLocaleDateString()}.xlsx`);
    
    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败", error);
    ElMessage.error("导出失败，请重试");
  }
};

// 导出明细
const handleExportDetail = () => {
  if (selectedRecords.value.length === 0) {
    ElMessage.warning("暂无数据可导出");
    return;
  }

  try {
    // 准备导出数据
    const exportData = selectedRecords.value.map(item => ({
      '订单号': item.orderNo,
      '交易流水号': item.transactionNo,
      '支付渠道': getChannelLabel(item.channel),
      '订单金额': item.orderAmount.toFixed(2),
      '实收金额': item.actualAmount.toFixed(2),
      '差异金额': item.difference.toFixed(2),
      '交易时间': item.createTime,
      '对账状态': getStatusLabel(item.status)
    }));

    // 创建工作簿
    const wb = XLSX.utils.book_new();
    
    // 将数据转换为工作表
    const ws = XLSX.utils.json_to_sheet(exportData);
    
    // 设置列宽
    const colWidths = [
      { wch: 25 }, // 订单号
      { wch: 25 }, // 交易流水号
      { wch: 15 }, // 支付渠道
      { wch: 15 }, // 订单金额
      { wch: 15 }, // 实收金额
      { wch: 15 }, // 差异金额
      { wch: 20 }, // 交易时间
      { wch: 15 }  // 对账状态
    ];
    ws['!cols'] = colWidths;
    
    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(wb, ws, "对账明细");
    
    // 生成并下载Excel文件
    XLSX.writeFile(wb, `对账明细_${new Date().toLocaleDateString()}.xlsx`);
    
    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败", error);
    ElMessage.error("导出失败，请重试");
  }
};

// 取消对账
const handleCancelReconciliation = () => {
  ElMessageBox.confirm("确定要取消本次对账操作吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      reconciliationDialogVisible.value = false;
      reconciliationForm.processType = "confirm";
      reconciliationForm.differenceRemark = "";
      reconciliationForm.remark = "";
      reconciliationForm.operator = "";
    })
    .catch(() => {});
};

// 确认对账
const handleConfirmReconciliation = () => {
  if (!reconciliationFormRef.value) return;

  reconciliationFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        reconciliationLoading.value = true;

        // 构建对账数据
        const reconciliationData = {
          records: selectedRecords.value.map((record) => ({
            id: record.id,
            orderNo: record.orderNo,
            transactionNo: record.transactionNo,
            difference: record.difference,
          })),
          processType: reconciliationForm.processType,
          differenceRemark: reconciliationForm.differenceRemark,
          remark: reconciliationForm.remark,
          operator: reconciliationForm.operator,
          totalAmount: getTotalOrderAmount(),
          totalActualAmount: getTotalActualAmount(),
          totalDifference: getTotalDifference(),
        };

        // 调用对账API
        const res = await service.post('/admin/finance/reconciliation/process', reconciliationData);
        
        if (res.code === 200) {
          ElMessage.success("对账完成");
          reconciliationDialogVisible.value = false;
          // 重置表单
          reconciliationForm.processType = "confirm";
          reconciliationForm.differenceRemark = "";
          reconciliationForm.remark = "";
          reconciliationForm.operator = "";
          // 刷新列表
          handleSearch();
        } else {
          ElMessage.error(res.message || "对账失败，请重试");
        }
      } catch (error) {
        console.error("对账失败", error);
        ElMessage.error("对账失败，请重试");
      } finally {
        reconciliationLoading.value = false;
      }
    }
  });
};

// 单条记录对账
const handleSingleReconciliation = (row) => {
  selectedRecords.value = [row];
  reconciliationDialogVisible.value = true;
};

// 初始化数据
onMounted(() => {
  handleSearch();
});
</script>

<style lang="scss" scoped>
.reconciliation-management {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .statistics-cards {
    margin-bottom: 20px;

    .stat-card {
      .stat-content {
        display: flex;
        align-items: center;
        padding: 20px;

        .stat-icon {
          width: 48px;
          height: 48px;
          border-radius: 8px;
          background-color: var(--el-color-primary-light-9);
          color: var(--el-color-primary);
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 16px;
          font-size: 24px;

          &.warning {
            background-color: var(--el-color-warning-light-9);
            color: var(--el-color-warning);
          }

          &.success {
            background-color: var(--el-color-success-light-9);
            color: var(--el-color-success);
          }

          &.info {
            background-color: var(--el-color-info-light-9);
            color: var(--el-color-info);
          }
        }

        .stat-info {
          flex: 1;

          .stat-title {
            font-size: 14px;
            color: var(--el-text-color-secondary);
            margin-bottom: 8px;
          }

          .stat-amount {
            font-size: 24px;
            font-weight: bold;
            color: var(--el-text-color-primary);
          }
        }
      }
    }
  }

  .search-section {
    background-color: var(--el-fill-color-light);
    padding: 24px;
    border-radius: 4px;
    margin-bottom: 20px;
  }

  .text-danger {
    color: var(--el-color-danger);
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .detail-section {
    h4 {
      margin: 0 0 16px;
      font-size: 16px;
      font-weight: 500;
    }
  }

  .mt-4 {
    margin-top: 16px;
  }

  .mb-4 {
    margin-bottom: 16px;
  }

  .reconciliation-summary {
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      h4 {
        margin: 0;
        font-size: 16px;
        font-weight: 500;
      }
    }

    .reconciliation-records {
      .difference-row {
        background-color: var(--el-color-danger-light-9);
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }

  /* 空状态样式 */
  .empty-state {
    padding: 40px 0;
    text-align: center;
  }

  .empty-text {
    font-size: 16px;
    color: var(--el-text-color-secondary);
    margin-top: 10px;
  }

  .empty-subtext {
    font-size: 14px;
    color: var(--el-text-color-placeholder);
    margin-top: 5px;
  }
}
</style>
